package com.zqxx.examine.portal.controller.page;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.zqxx.examine.common.utils.Page;
import com.zqxx.examine.common.utils.QuestionAdapter;
import com.zqxx.examine.model.exam.AnswerSheet;
import com.zqxx.examine.model.exam.AnswerSheetItem;
import com.zqxx.examine.model.exam.Exam;
import com.zqxx.examine.model.exam.ExamHistory;
import com.zqxx.examine.model.exam.ExamPaper;
import com.zqxx.examine.model.question.KnowledgePoint;
import com.zqxx.examine.model.question.QuestionQueryResult;
import com.zqxx.examine.model.question.QuestionStatistic;
import com.zqxx.examine.portal.security.UserInfo;
import com.zqxx.examine.portal.service.ExamPaperService;
import com.zqxx.examine.portal.service.ExamService;
import com.zqxx.examine.portal.service.QuestionHistoryService;
import com.zqxx.examine.portal.service.QuestionService;

@Controller
public class ExamPage
{
  @Autowired
  private ExamService examService;
  @Autowired
  private ExamPaperService examPaperService;
  @Autowired
  private QuestionHistoryService questionHistoryService;
  @Autowired
  private QuestionService questionService;
  
  @RequestMapping(value={"/exam-list"}, method={org.springframework.web.bind.annotation.RequestMethod.GET})
  public String examListPage(Model model, HttpServletRequest request)
  {
    int userId = 0;
    if ((SecurityContextHolder.getContext().getAuthentication() != null) && (!SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString().endsWith("anonymousUser")))
    {
      UserInfo userInfo = (UserInfo)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
      userId = userInfo.getUserid();
    }
    Page<Exam> page = new Page();
    page.setPageSize(10);
    page.setPageNo(1);
    List<Exam> examListToApply = this.examService.getExamListToApply(userId, page);
    List<Exam> examListToStart = this.examService.getExamListToStart(userId, null, new int[] { 1, 2 });
    List<Exam> modelTestToStart = this.examService.getExamList(null, new int[] { 3 });
    model.addAttribute("examListToApply", examListToApply);
    model.addAttribute("examListToStart", examListToStart);
    model.addAttribute("modelTestToStart", modelTestToStart);
    model.addAttribute("userId", Integer.valueOf(userId));
    return "exam";
  }
  
  @RequestMapping(value={"/student/exam-start/{examId}"}, method={org.springframework.web.bind.annotation.RequestMethod.GET})
  public String examStartPage(Model model, HttpServletRequest request, @PathVariable("examId") int examId)
  {
    UserInfo userInfo = (UserInfo)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    
    String strUrl = "http://" + request.getServerName() + ":" + request.getServerPort() + "/";
    
    int duration = 0;
    Exam exam = this.examService.getExamById(examId);
    if ((exam.getApproved() != 1) || (exam.getExpTime().before(new Date())) || (exam.getExamType() == 3))
    {
      model.addAttribute("errorMsg", "考试未审核或当前时间不能考试或考试类型错误");
      return "error";
    }
    ExamHistory examHistory = this.examService.getUserExamHistByUserIdAndExamId(userInfo.getUserid(), examId, new int[] { 0, 1, 2, 3 });
    Date startTime = examHistory.getStartTime() == null ? new Date() : examHistory.getStartTime();
    switch (examHistory.getApproved())
    {
    case 0: 
      model.addAttribute("errorMsg", "考试未审核");
      return "error";
    case 2: 
      model.addAttribute("errorMsg", "已交卷，不能重复考试");
      return "error";
    case 3: 
      model.addAttribute("errorMsg", "已阅卷，不能重复考试");
      return "error";
    }
    ExamPaper examPaper = this.examPaperService.getExamPaperById(examHistory.getExamPaperId());
    String content = examPaper.getContent();
    
    Gson gson = new Gson();
    duration = examPaper.getDuration();
    
    List<QuestionQueryResult> questionList = (List)gson.fromJson(content, new TypeToken() {}.getType());
    StringBuilder sb = new StringBuilder();
    for (QuestionQueryResult question : questionList)
    {
      QuestionAdapter adapter = new QuestionAdapter(question, strUrl);
      sb.append(adapter.getUserExamPaper());
    }
    model.addAttribute("startTime", startTime);
    model.addAttribute("examHistoryId", Integer.valueOf(examHistory.getHistId()));
    model.addAttribute("examId", Integer.valueOf(examHistory.getExamId()));
    model.addAttribute("examPaperId", Integer.valueOf(examHistory.getExamPaperId()));
    model.addAttribute("duration", Integer.valueOf(duration * 60));
    model.addAttribute("htmlStr", sb.toString());
    
    userInfo.setHistId(0);
    return "examing";
  }
  
  @RequestMapping(value={"/student/model-test-start/{examId}"}, method={org.springframework.web.bind.annotation.RequestMethod.GET})
  public String modelTestStartPage(Model model, HttpServletRequest request, @PathVariable("examId") int examId)
  {
    UserInfo userInfo = (UserInfo)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    
    String strUrl = "http://" + request.getServerName() + ":" + request.getServerPort() + "/";
    
    int duration = 0;
    Exam exam = this.examService.getExamById(examId);
    if ((exam.getApproved() != 1) || (exam.getExpTime().before(new Date())) || (exam.getExamType() != 3))
    {
      model.addAttribute("errorMsg", "考试未审核或当前时间不能考试或考试类型错误");
      return "error";
    }
    ExamPaper examPaper = this.examPaperService.getExamPaperById(exam.getExamPaperId());
    
    ExamHistory examHistory = this.examService.getUserExamHistByUserIdAndExamId(userInfo.getUserid(), examId, new int[] { 0, 1, 2, 3 });
    int historyId = 0;
    if (examHistory == null) {
      historyId = this.examService.addUserExamHist(userInfo.getUserid(), examId, examPaper.getId(), 1);
    } else {
      historyId = examHistory.getHistId();
    }
    String content = examPaper.getContent();
    
    Gson gson = new Gson();
    duration = examPaper.getDuration();
    
    List<QuestionQueryResult> questionList = (List)gson.fromJson(content, new TypeToken() {}.getType());
    StringBuilder sb = new StringBuilder();
    for (QuestionQueryResult question : questionList)
    {
      QuestionAdapter adapter = new QuestionAdapter(question, strUrl);
      sb.append(adapter.getUserExamPaper());
    }
    model.addAttribute("examHistoryId", Integer.valueOf(historyId));
    model.addAttribute("examId", Integer.valueOf(examId));
    model.addAttribute("examPaperId", Integer.valueOf(examPaper.getId()));
    model.addAttribute("duration", Integer.valueOf(duration * 60));
    model.addAttribute("htmlStr", sb.toString());
    userInfo.setHistId(0);
    return "examing";
  }
  
  @RequestMapping(value={"/student/student-answer-sheet/{examId}"}, method={org.springframework.web.bind.annotation.RequestMethod.GET})
  private String studentAnswerSheetPage(Model model, HttpServletRequest request, @PathVariable int examId)
  {
    UserInfo userInfo = (UserInfo)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    ExamHistory history = this.examService.getUserExamHistByUserIdAndExamId(userInfo.getUserid(), examId, new int[] { 2, 3 });
    int examPaperId = history.getExamPaperId();
    

    String strUrl = "http://" + request.getServerName() + ":" + request.getServerPort() + "/";
    
    ExamPaper examPaper = this.examPaperService.getExamPaperById(examPaperId);
    StringBuilder sb = new StringBuilder();
    if ((examPaper.getContent() != null) && (!examPaper.getContent().equals("")))
    {
      Gson gson = new Gson();
      String content = examPaper.getContent();
      List<QuestionQueryResult> questionList = (List)gson.fromJson(content, new TypeToken() {}.getType());
      for (QuestionQueryResult question : questionList)
      {
        QuestionAdapter adapter = new QuestionAdapter(question, strUrl);
        sb.append(adapter.getStringFromXML());
      }
    }
    model.addAttribute("htmlStr", sb);
    model.addAttribute("exampaperid", Integer.valueOf(examPaperId));
    model.addAttribute("examHistoryId", Integer.valueOf(history.getHistId()));
    model.addAttribute("exampapername", examPaper.getName());
    model.addAttribute("examId", Integer.valueOf(history.getExamId()));
    return "student-answer-sheet";
  }
  
  @RequestMapping(value={"student/finish-exam/{examId}"}, method={org.springframework.web.bind.annotation.RequestMethod.GET})
  public String examFinishedPage(Model model, @PathVariable("examId") int examId)
  {
    UserInfo userInfo = (UserInfo)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    
    ExamHistory history = this.examService.getUserExamHistByUserIdAndExamId(userInfo.getUserid(), examId, new int[] { 2, 3 });
    Gson gson = new Gson();
    List<QuestionQueryResult> questionList = (List)gson.fromJson(history.getContent(), new TypeToken() {}.getType());
    List<Integer> idList = new ArrayList();
    for (QuestionQueryResult q : questionList) {
      idList.add(Integer.valueOf(q.getQuestionId()));
    }
    AnswerSheet as = (AnswerSheet)gson.fromJson(history.getAnswerSheet(), AnswerSheet.class);
    
    HashMap<Integer, AnswerSheetItem> hm = new HashMap();
    for (AnswerSheetItem item : as.getAnswerSheetItems()) {
      hm.put(Integer.valueOf(item.getQuestionId()), item);
    }
    int total = questionList.size();
    int wrong = 0;
    int right = 0;
    
    HashMap<Integer, QuestionStatistic> reportResultMap = new HashMap();
    List<QuestionQueryResult> questionQueryList = this.questionService.getQuestionAnalysisListByIdList(idList);
    Map<Integer, KnowledgePoint> pointMap = this.questionService.getKnowledgePointByFieldId(null, new int[0]);
    HashMap<Integer, Boolean> answer = new HashMap();
    for (QuestionQueryResult result : questionQueryList)
    {
      QuestionStatistic statistic = (QuestionStatistic)reportResultMap.get(Integer.valueOf(result.getKnowledgePointId()));
      if (statistic == null) {
        statistic = new QuestionStatistic();
      }
      statistic.setPointId(result.getKnowledgePointId());
      statistic.setPointName(((KnowledgePoint)pointMap.get(Integer.valueOf(result.getKnowledgePointId()))).getPointName());
      statistic.setAmount(statistic.getAmount() + 1);
      if (((AnswerSheetItem)hm.get(Integer.valueOf(result.getQuestionId()))).isRight())
      {
        statistic.setRightAmount(statistic.getRightAmount() + 1);
        right++;
        answer.put(Integer.valueOf(result.getQuestionId()), Boolean.valueOf(true));
      }
      else
      {
        statistic.setWrongAmount(statistic.getWrongAmount() + 1);
        wrong++;
        answer.put(Integer.valueOf(result.getQuestionId()), Boolean.valueOf(false));
      }
      total++;
      reportResultMap.put(Integer.valueOf(result.getKnowledgePointId()), statistic);
    }
    model.addAttribute("total", Integer.valueOf(total));
    model.addAttribute("wrong", Integer.valueOf(wrong));
    model.addAttribute("right", Integer.valueOf(right));
    model.addAttribute("reportResultMap", reportResultMap);
    model.addAttribute("create_time", history.getCreateTime());
    model.addAttribute("answer", answer);
    model.addAttribute("idList", idList);
    return "exam-finished";
  }
  
  @RequestMapping(value={"student/finished-submit"}, method={org.springframework.web.bind.annotation.RequestMethod.GET})
  public String finishedSubmitPage(Model model)
  {
    return "finished-submit";
  }
}
